package com.huanzhidadi.redis.redisson;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Redisson实现分布式锁
 */
@Slf4j
public class RedissonLock {

    private static volatile RedissonClient redissonClient;

    private static RedissonClient newClient() {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://192.168.2.132:6311");
        // singleServerConfig.setPassword("123456");
        return Redisson.create(config);
    }

    public static RedissonClient getRedissonClient() {
        if (null == redissonClient) {
            synchronized (Object.class) {
                if (null == redissonClient) {
                    redissonClient = newClient();
                }
            }
        }
        return redissonClient;
    }

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        for (int i=0; i<5; i++) {
            pool.execute(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    RedissonClient client = getRedissonClient();
                    RLock lckAcc000 = client.getLock("lck_acc_000");
                    lckAcc000.lock(30, TimeUnit.SECONDS);
                    int i = new Random().nextInt(1000);
                    log.info("-acc_{}账户减少{}元", i, i);
                    Thread.sleep(i);
                    log.info("+结算账户acc_000增加{}元", i);
                    lckAcc000.unlock();
                }
            });
        }
    }
}
